const  util = require("util")

function splitItem(item){
  const phone = item.get('phone')
  if(phone && !item.get('brand')){
    const list = phone.split('\n')
    const productTime = list[1].split(':').slice(1).join(':')
    const bm = list[3].split(':')[1].trim()
    const brandModel = bm.split(' ')
    item.set('productTime',productTime)
    item.set('brandModel',bm)
    item.set('imei', list[2].split(':')[1].trim())
    item.set('brand', brandModel.shift())
    item.set('model', brandModel.filter(item => item).join('-'))
  }
  
}


Parse.Cloud.job('fixedRoTaskLastTime',async (req,status)=>{
  try{
    const q = new Parse.Query('RoTask')
    q.equalTo('done',1)
    q.limit(20000)
    
    const list = await q.find()
  
    list.forEach(item=>{
        const st = item.get('startTime')
        const et = item.get('endTime')
        const lastTime = Math.round((et-st)/1000)
        if(util.isNumber(lastTime)){
            item.set('lastTime',lastTime) 
        }
      }
    )
       
    await Parse.Object.saveAll(list)

    status.success()
  } catch (err) {
    status.error()
  }
     
})

Parse.Cloud.job('findCanSaleMomoId',async (req,status)=>{
  try{
    const q = new Parse.Query('RoTask')
    q.equalTo('done',1)
    q.notEqualTo('exported',true)   
    q.doesNotExist('canSale')
    q.ascending('endTime')
    q.limit(1000)
    
    const list = await q.find()
    const now = new Date()
    list.forEach(item=>{
        const ft = item.get('endTime')
        if(ft){
          const d = (now.getTime() - ft.getTime()) /(24*3600*1000)
          const days=Math.floor(d)
          if(days>=1){
              item.set('canSale',true)
          }else{
              item.set('canSale',false)
          }
        }
    })
    await Parse.Object.saveAll(list)

    status.success()
  } catch (err) {
    status.error()
  }
     
})

Parse.Cloud.job('splitRoTaskPhone', async (req, status) => {
  try {
    console.log('in>>>>>')
    const tasks = await new Parse.Query('RoTask').exists('phone').limit(1000000).find({useMasterKey: true})
    console.log(tasks)
    tasks.forEach((item) => {
       splitItem(item)
    })
    await Parse.Object.saveAll(tasks, {useMasterKey: true})
    console.log('ok')
    status.success()
  } catch (err) {
    console.log(err)
    status.error()
  }
})

// Parse.Cloud.beforeSave('RoTask', async (req, res) => {
//   try {
//     const roTask = req.object
//     // splitItem(roTask)

//     if(roTask.get('endTime') && !roTask.get('y')){
//       const t = roTask.get('endTime')
//       const y = t.getFullYear()
//       const m = t.getMonth()+1
//       const d = t.getDate()
//       const h = t.getHours()
//       roTask.set('y',y)
//       roTask.set('m',m)
//       roTask.set('d',d)
//       roTask.set('h',h)
//     }
//     res.success(roTask)
//   } catch (err) {
//     res.error(err)
//   }
// })

